<!--新增功能，上半部分表单-->
<template>
  <div class="upload-multi-box">
    <!-- 上传 -->
    <div v-if="!isViewMode" class="uploader-wrapper">
      <el-upload
        v-bind="imgAttr"
        class="dialog-upload"
        action="string"
        multiple
        :show-file-list="false"
        accept="image/*"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeUpload"
        :http-request="toRequest"
        fit="scale-down"
      >
        <el-image v-if="imagesurlstr" fit="cover" :src="imagesurlstr" />
        <div v-else class="tip-box">
          <div class="tip-uploader">
            <i class="el-icon-plus avatar-uploader-icon" />
          </div>
          <p class="tip-font">（支持jpg/png，上传图片5张以内，总计5M内）</p>
        </div>
      </el-upload>
    </div>
    <div class="qrcode-upload-box">
      <m-upload
        v-if="!isViewMode"
        action="uploadUrl"
        :m-props="{urlObj: qrcodeImg, urlStr: 'url'}"
        :on-success="handleAvatarSuccess"
        :before-upload="startAvatarUpload"
        :http-request="toRequest"
      />
    </div>

    <!-- 图片 删除 重新上传 -->
    <div
      v-for="(item, index) in imagesurlarr"
      :key="index"
      class="image-wrapper"
      :class="isViewMode ? 'view-only' : ''"
      v-viewer
    >
      <el-image fit="cover" :src="item" class="image-item" />
      <span class="delete-icon" @click="deleteImg(index)">
        <i class="el-icon-circle-close" />
      </span>
    </div>
  </div>
</template>

<script>
import {fileUpload} from '../../const/api.js'
import {fitType} from '../../const/common.js'
import {without} from 'lodash'
import {setImmediate} from 'timers'
// 文件上传限制 ------- 图片类型
const imageLimit = 'image/'
export default {
  name: 'PictureUpload',
  props: {
    // 接收默认url
    imgsrc: {
      type: String,
      default: () => ''
    },
    // 接收多张
    imgsrcarr: {
      type: Array,
      default: () => []
    },
    // 跟单独调用没有关系，该值为了配合表单组件使用
    keystr: {
      type: String,
      default: () => ''
    },
    // 类型, 1 为多张图片
    uptype: {
      type: String,
      default: '1'
    },
    // 上传属性
    attr: {
      type: Object,
      default: () => {}
    },
    max: {
      // 最大可上传的张数
      type: Number,
      default: 5
    },
    fileList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 类型
      type: this.uptype || '',
      // 该值为了配合表单组件使用
      key: this.keystr || '',
      // 图片填充行为
      fitType,
      // 上传的地址
      uploadUrl: fileUpload,
      // 多张上传的图片地址
      imagesurlarr: this.imgsrcarr || [],
      // 单张
      imagesurlstr: this.imgsrc || '',
      // 上传属性
      imgAttr: {},
      fileArr: [],
      qrcodeImg: {
        url: ''
      }
    }
  },
  computed: {
    isViewMode() {
      return this.imgAttr.disabled
    }
  },
  methods: {
    //   删除文件
    deleteImg(index) {
      this.imagesurlarr.splice(index, 1)
      this.$emit('ReturnImgUrl', this.imagesurlarr, this.key)
      this.fileArr.splice(index, 1)
      this.$emit('ReturnFileArr', this.fileArr, this.key)
    },
    // 上传图片成功 本地图片地址
    handleAvatarSuccess(res, file) {
      this.localImgurl = URL.createObjectURL(file.raw)
    },
    // 图片上传前
    startAvatarUpload(file) {
      // 条件拦截
      this.uploadActon(file, 'produce')
    },
    // 点击上传
    beforeUpload(file) {
      // 图片拦截
      const isJPG = file.type.includes(imageLimit)
      if (!isJPG) {
        this.$message.error('上传证照图片只能是图片格式!')
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!isLt2M) {
        this.$message.error('上传证照图片大小不能超过 1MB!')
        return false
      }
    },
    toRequest(data) {
      if (this.imagesurlarr.length === this.max) {
        this.$message.warning(`最多只支持上传${this.max}张图片！`)
        return
      }
      // 发起请求
      let fd = new FormData()
      fd.append('file', data.file)
      this.$axios({
        method: 'post',
        url: fileUpload,
        headers: {'Content-Type': 'multipart/form-data'},
        data: fd
      }).then(res => {
        this.$message({type: 'success', message: '上传成功'})
        // 赋值上传后的地址给文档
        const currentImgUrl = res.data.payload
        if (this.type === '1') {
          this.imagesurlarr.push(currentImgUrl)
          let obj = {
            fileName: data.file.name.split('.')[0],
            url: currentImgUrl
          }
          this.fileArr.push(obj)
          this.$emit('ReturnImgUrl', this.imagesurlarr, this.key)
          this.$emit('ReturnFileArr', this.fileArr, this.key)
        } else {
          this.imagesurlstr = res.data.payload
          this.$emit(
            'ReturnImgUrl',
            this.imagesurlstr,
            this.key,
            data.file.name
          )
        }
      })
    }
  },
  watch: {
    fileList: {
      handler(val) {
        this.fileArr = val
      }
    },
    imgsrc: {
      immediate: true,
      handler(val) {
        this.imagesurlstr = val
      }
    },
    imgsrcarr: {
      handler(val) {
        this.imagesurlarr = val
      },
      immediate: true
    },
    attr: {
      immediate: true,
      handler(val) {
        this.imgAttr = val
      }
    },
    'qrcodeImg.url'(val) {
      if (!val) return
      if (this.imagesurlarr.length === this.max) {
        this.$message.warning(`最多只支持上传${this.max}张图片！`)
        return
      }
      this.imagesurlarr.push(val)
      this.qrcodeImg.url = ''
    }
  }
}
</script>

<style lang="less">
.upload-multi-box {
  display: flex;
  // flex-flow: row wrap;
  .uploader-wrapper {
    position: relative;
    width: 210px;
    .tip-box {
      display: flex;
      flex-direction: column;
      align-items: center;
      .tip-uploader {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        border: 1px solid #cdd2dc;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 22px;
        color: #2371c5;
      }
    }
  }
  .qrcode-upload-box {
    position: absolute;
    top: 0;
    left: 190px;
  }
  .image-wrapper {
    position: relative;
    width: 180px;
    margin: 7px;
    padding: 10px;
    border: 1px dashed #cdd2dc;
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: center;
    img {
      max-width: 160px;
    }
    .delete-icon {
      display: none;
    }
    &:hover {
      .delete-icon {
        display: inline;
        position: absolute;
        top: -5px;
        right: 0;
        font-size: 22px;
        color: #cdd2dc;
        &:hover {
          color: fade(#2371c5, 60%);
          cursor: pointer;
        }
      }
    }
    &.view-only {
      border: 1px solid #cdd2dc;
      &:hover {
        .delete-icon {
          display: none;
        }
      }
    }
  }
}
</style>
